package gameEntities;

import constants.Constants;

import javax.microedition.lcdui.game.Sprite;

import math.Vector2D;

/**
 * The Class Bait.
 */
public class Bait extends MovingGameEntity {

	/**
	 * Instantiates a new bait.
	 *
	 * @param sprite the sprite
	 * @param position the position
	 */
	public Bait(Sprite sprite, Vector2D position) {
		super(sprite, position);

		velocity.x = velocity.y = 0.0f;
		initialPosition = position.duplicate();
		stringLength = -1.f;
		reelIn = false;
	}
	
	/**
	 * Cast.
	 *
	 * @param v the v
	 */
	public void Cast(Vector2D v) {
		if (IsFullyReeledIn()) {// can only cast when bait is fully reeled in
			velocity.x = v.x;
			velocity.y = v.y;
		}
	}
	
	/**
	 * Sets reel in to true.
	 */
	public void ReelIn() {
		reelIn = true;
	}
	
	/**
	 * Checks if is fully reeled in.
	 *
	 * @return true, if is fully reeled in
	 */
	public boolean IsFullyReeledIn() {
		if (initialPosition.quadDistance(position) > 200.0f)
			return false;
		return true;
	}
	
	/* (non-Javadoc)
	 * @see gameEntities.MovingGameEntity#Update(float)
	 */
	public void Update(float deltaTime) {
		super.Update(deltaTime);
		
		// if bait hits water, set string length
		if (position.y > Constants.WATERLEVEL && stringLength < .0f) {
			stringLength = initialPosition.quadDistance(position);
		}
		
		// gravity
		if (!IsFullyReeledIn())
			velocity.y += 0.55f;
		
		// dampen
		if (position.y > Constants.WATERLEVEL)  {
			// in water
			velocity.x *= .992f;
			velocity.y *= .992f;
		} else {
			// in air
			velocity.x *= .9999f;
			velocity.y *= .9999f;
		}
		
		// clamp to distance of string length
		// inaccurate calculations because a real Square root is too expensive
		if (stringLength > .0f) {
			if (initialPosition.quadDistance(position) - stringLength > .0f) {
				Vector2D f = initialPosition.duplicate();
				f.sub(position);
				float max = (math.Math.abs(f.x) > math.Math.abs(f.y)) ? math.Math.abs(f.x) : math.Math.abs(f.y);
				f.x /= max;
				f.y /= max;
				position.x += f.x;
				position.y += f.y;
			}
		} else if (stringLength == .0f) {
			Reset();
		}
		
		if (reelIn && stringLength > .0f) {
			stringLength -= 50000.0f * deltaTime;
			if (stringLength < .0f)
				stringLength = .0f;
			reelIn = false;
		}
	}
	
	/**
	 * Reset the bait.
	 */
	private void Reset() {
		velocity.x = velocity.y = .0f;
		position.x = initialPosition.x;
		position.y = initialPosition.y;
		stringLength = -1;
	}
	
	private Vector2D initialPosition;
	
	private float stringLength;
	
	private boolean reelIn;

}
